package edu.mse.camel.client.uml.collab.handlers;

import java.util.ArrayList;
import java.util.List;

import edu.mse.camel.client.core.events.model.ModelUpdateEvent;
import edu.mse.camel.client.core.events.model.ModelUpdateEvent2;
import edu.mse.camel.client.eventbus.pubsub.EventManager;
import edu.mse.camel.client.eventbus.pubsub.ISubscriber;
import edu.mse.camel.client.events.EventIDs;
import edu.mse.camel.client.events.IEvent;
import edu.mse.camel.client.events.peer.ReceiveGenericPeerEvent;
import edu.mse.camel.client.events.peer.ViewportChangeEvent;
import edu.mse.camel.client.uml.collab.loginstate.SessionState;

public class GenericReceiveEventHandler implements ISubscriber {
	
	private List<ModelUpdateEvent2> tempEventList = new ArrayList<ModelUpdateEvent2>();

	public GenericReceiveEventHandler() {
		EventManager.getInstance().subscribeTo(EventIDs.RECEIVE_PEER_EVENT, this);
	}
	
	public synchronized void publishQueuedModelUpdates () {
		for (ModelUpdateEvent2 event : tempEventList) {
			EventManager.getInstance().dispatchEventAsynchronous(event);
		}
		tempEventList.clear();
	}
	
	@Override
	public synchronized void notifyEvent(IEvent event) {
		if (event instanceof ReceiveGenericPeerEvent) {
			ReceiveGenericPeerEvent genericEvent = (ReceiveGenericPeerEvent) event;
			if ( genericEvent.getDataType().equals(ModelUpdateEvent2.class.getCanonicalName())) {
				ModelUpdateEvent2 me = genericEvent.readObject(ModelUpdateEvent2.class);
				if(SessionState.targetViewAvailable) {
					EventManager.getInstance().dispatchEventAsynchronous(me);
				}
				else {
					tempEventList.add(me);
				}
			}
			if ( genericEvent.getDataType().equals(ModelUpdateEvent.class.getCanonicalName())) {
				ModelUpdateEvent me = genericEvent.readObject(ModelUpdateEvent.class);
				EventManager.getInstance().dispatchEventAsynchronous(me);
			}
			if ( genericEvent.getDataType().equals(ViewportChangeEvent.class.getCanonicalName())) {
				ViewportChangeEvent vp = genericEvent.readObject(ViewportChangeEvent.class);
				vp.userID = genericEvent.getUserID(); //IMPORTANT
				EventManager.getInstance().dispatchEventAsynchronous(vp);
			}
			else {
				// it should be okay that we do not understand the actual data type of a generic event
			}
		}
	}

}
